package com.example.composewanandroid.ui.screens.home.explore

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.example.composewanandroid.data.repository.HomeRepository
import com.example.composewanandroid.network.model.ArticleList
import com.example.composewanandroid.network.model.Banner
import com.example.composewanandroid.network.viewmodel.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ExploreViewModel @Inject constructor(private val repository: HomeRepository) :
    BaseViewModel() {
//    init {//不能直接这样写，init快于lazy？？？
//        getHomeBanner()//请求Banner数据
//        getHomeInfoList(20)//请求首页数据
//    }

    private val homeRepository by lazy { HomeRepository() }


    private val _articleList = MutableStateFlow<ArticleList?>(null)
    val articleList = _articleList.asStateFlow()

    private val _bannerList = MutableStateFlow<List<Banner>?>(null)
    val bannerList = _bannerList.asStateFlow()

    /**
     * 首页列表
     * @param page 页码
     */
    fun getHomeInfoList(page: Int) {
        viewModelScope.launch {
            val response = safeApiCall(errorBlock = { code, errorMsg ->
                Log.d("wenlong", "getHomeInfoList:${errorMsg} ")
            }) {
                homeRepository.getHomeInfoList(page)
            }
            response?.let {
                _articleList.value = it
            }
        }
    }

    /**
     * 请求
     */
    fun getHomeBanner() {
        viewModelScope.launch {
            val response = safeApiCall(errorBlock = { code, errorMsg ->
                Log.d("wenlong", "getHomeBanner:${errorMsg} ")
            }) {
                homeRepository.getHomeBanner()
            }
            response?.let {
                _bannerList.value = it
            }
        }
    }
}

